package me.android.library.ui.config;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import java.io.IOException;
import java.io.InputStream;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import me.android.library.utils.android.SystemServiceUtil;
import mylab.utils.common.YamlUtil;

@Slf4j
@UtilityClass
public class UiConfigUtil {

    final String UI_CONFIG_FILE = "ui.yml";

    public static UiConfig loadFromAsset() {
        return loadFromAsset(UI_CONFIG_FILE);
    }

    public static UiConfig loadFromAsset(String fileName) {
        try (InputStream in = SystemServiceUtil.getAssetManager().open(fileName)) {
            UiConfig uiConfig = YamlUtil.loadAs(in, UiConfig.class);
            check(uiConfig);
            return uiConfig;
        } catch (IOException e) {
            log.warn("loadFromAsset error", e);
            return null;
        }
    }

    public static UiConfig loadFromString(String configContent) {
        UiConfig uiConfig = YamlUtil.loadAs(configContent, UiConfig.class);
        check(uiConfig);
        return uiConfig;
    }


    private void check(UiConfig uiConfig) {
        Preconditions.checkState(!Strings.isNullOrEmpty(uiConfig.getMain()), "mainFormKey is null");
    }


}
